/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.kosongkosong.scheduler;

import com.google.api.GoogleAPI;
import com.google.api.translate.Language;
import com.google.api.translate.Translate;
import com.kosongkosong.model.Story;
import com.kosongkosong.model.id.StoryId;
import com.kosongkosong.service.DataService;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 *
 * @author ifnu
 */
@Controller
public class TranslatorScheduler {

    static{
        GoogleAPI.setHttpReferrer("http://kosong-kosong.appspot.com");
    }

    @Autowired private DataService dataService;

    @RequestMapping(value="/translate-news",method=RequestMethod.GET)
    public void parseHeadLine(HttpServletResponse response) throws Exception{
        //one story at a time
        List<Story> stories = dataService.getStories();
        for (Story story : stories) {
            StoryId storyId = dataService.getStoryId(story.getId());
            if(storyId == null&&
                    (story.getFullStory()!=null
                    || story.getSubHeader()!=null
                    || story.getHeader()!=null)){
                storyId  = new StoryId();
                if(story.getFullStory()!=null){
                    storyId.setFullStory(Translate.execute(story.getFullStory(),
                        Language.ENGLISH, Language.INDONESIAN));
                }
                if(story.getHeader()!=null){
                    storyId.setHeader(Translate.execute(story.getHeader(),
                            Language.ENGLISH, Language.INDONESIAN));
                }
                if(story.getSubHeader()!=null){
                    storyId.setSubHeader(Translate.execute(story.getSubHeader(),
                        Language.ENGLISH, Language.INDONESIAN));
                }
                storyId.setHeadline(story.getHeadline());
                storyId.setId(story.getId());
                storyId.setImageUrl(story.getImageUrl());
                storyId.setStoryUrl(story.getStoryUrl());
                dataService.save(storyId);
                break;
            }
        }
    }


}
